package com.example.administrator.capital.item;


import android.app.Fragment;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.administrator.capital.R;
import com.example.administrator.capital.adapter.callback.OnPopWinDisMisBack;
import com.example.administrator.capital.base.BaseBackFragment;
import com.example.administrator.capital.eventbus.EventBase;
import com.example.administrator.capital.mine.RechargeFragment;
import com.example.administrator.capital.mine.second.SetDealPasswordFragment;
import com.example.administrator.capital.model.bean.DetailBean;
import com.example.administrator.capital.presenter.ItemsPresenter;
import com.example.administrator.capital.presenter.base.IViewRequest;
import com.example.administrator.capital.utils.DisPlayUtils;
import com.example.administrator.capital.utils.JsonUtils;
import com.example.administrator.capital.utils.PreferenceManager;
import com.example.administrator.capital.utils.ToastUtil;
import com.example.administrator.capital.widget.CustomPopupWindow;
import com.lzy.okgo.model.Response;

import org.greenrobot.eventbus.Subscribe;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import eventbusactivityscope.EventBusActivityScope;

/**
 * A simple {@link Fragment} subclass.
 * 项目详情
 */
public class ItemDetailFragment extends BaseBackFragment {

    @BindView(R.id.item_information)
    TextView mItemInformation;
    @BindView(R.id.information_data)
    TextView mInformationData;
    @BindView(R.id.support_list)
    TextView mSupportList;
    @BindView(R.id.refund_information)
    TextView mRefundInformation;
    @BindView(R.id.tv_deposit)
    TextView mTvDeposit;
    @BindView(R.id.tv_lend)
    TextView mTvLend;
    @BindView(R.id.ll_bottom)
    LinearLayout mLlBottom;
    Unbinder unbinder;
    //    @BindView(R.id.loading)
//    LoadingLayout mLoading;
    @BindView(R.id.rate)
    TextView mRate;
    @BindView(R.id.fundamount)
    TextView mFundamount;
    @BindView(R.id.layout_exit)
    LinearLayout layoutExit;
    @BindView(R.id.buy_amount)
    TextView buyAmount;
    private int fundamount;
    private int orderamount;
    @BindView(R.id.timelimit)
    TextView mTimelimit;
    @BindView(R.id.edit_money)
    EditText editMoney;
    private TextView mBack;
    private CustomPopupWindow mCustomPopupWindow;
    private ItemsPresenter mItemsPresenter;
    private String baseinfo;
    private String content;
    private List<DetailBean.DataBean.RefundListBean> mRefundListBeans = new ArrayList<>();
    private List<DetailBean.DataBean.RepayListBean> mRepayListBeans = new ArrayList<>();
    private int uid;

    public ItemDetailFragment() {
        // Required empty public constructor
    }

    public static ItemDetailFragment newInstance(String proid) {

        Bundle args = new Bundle();
        args.putString("proid", proid);
        ItemDetailFragment fragment = new ItemDetailFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_item_detail, container, false);
        unbinder = ButterKnife.bind(this, view);
        return attachToSwipeBack(view);
    }

    @Override
    protected void initView(View view) {
        super.initView(view);
        mItemsPresenter = new ItemsPresenter(null);
        mBack = view.findViewById(R.id.app_title_back);
    }

    @Override
    protected void setListener() {
        super.setListener();
        mItemInformation.setOnClickListener(this);
        mInformationData.setOnClickListener(this);
        mSupportList.setOnClickListener(this);
        mRefundInformation.setOnClickListener(this);
        mBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                _mActivity.onBackPressed();
            }
        });
        mTvDeposit.setOnClickListener(this);
        mTvLend.setOnClickListener(this);
    }

    @Override
    protected void setData() {
        super.setData();
        getData(mBundle.getString("proid"));
    }

    /**
     * @param proid 项目详情
     */
    private void getData(String proid) {
        mItemsPresenter.details(new IViewRequest<String>() {
            @Override
            public void onFailMsg(String var) {
                ToastUtil.showShort(var);
//                mLoading.setEmptyImage(R.drawable.empty);
//                mLoading.setEmptyText(var);
//                mLoading.showEmpty();
            }

            @Override
            public void onCode(int code) {
                ToastUtil.showShort(code);
//                mLoading.setErrorImage(R.drawable.error);
//                mLoading.showError();
            }

            @Override
            public void onSuccess(Response<String> data) {
                DetailBean detailBean = JsonUtils.parse(data.body(), DetailBean.class);

                content = detailBean.getData().getContent();
                baseinfo = detailBean.getData().getBaseinfo();
                if (data.body().contains("refundList")) {
                    mRefundListBeans.clear();
                    mRefundListBeans.addAll(detailBean.getData().getRefundList());
                }
                if (data.body().contains("repayList")) {
                    mRepayListBeans.clear();
                    mRepayListBeans.addAll(detailBean.getData().getRepayList());
                }
                if (detailBean.getData().getFundamount()-detailBean.getData().getOrderamount() == 0) {
                    layoutExit.setVisibility(View.GONE);
                    buyAmount.setText(detailBean.getData().getBuyamount()+".0");
                } else {
                    buyAmount.setText(detailBean.getData().getBuyamount()/100+".0");
                    layoutExit.setVisibility(View.VISIBLE);
                }
                uid = detailBean.getData().getUid();
                mRate.setText(detailBean.getData().getRate());
                fundamount = detailBean.getData().getFundamount() / 100;
                mFundamount.setText(detailBean.getData().getFundamount() / 1000000 + "万");
                mTimelimit.setText(detailBean.getData().getRefundnum() + "个月");
            }

            @Override
            public void onFail(Response<String> error) {

            }
        }, proid);
    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.item_information:
                start(ItemInformationFragment.newInstance(baseinfo));
                break;
            case R.id.information_data:
                start(InformationDataFragment.newInstance(content));
                break;
            case R.id.support_list:
                start(SupportListFragment.newInstance((Serializable) mRefundListBeans));
                break;
            case R.id.refund_information:
                start(RefundInformationFragment.newInstance((Serializable) mRepayListBeans));
                break;
            case R.id.tv_deposit:
                start(RechargeFragment.newInstance());
                break;
            case R.id.tv_lend:
                if (buyAmount.getText().toString().equals("0.0")) {
                    ToastUtil.showShort("投资金额已到上限");
                }else {
                    if (uid == 0) {
                        start(SetDealPasswordFragment.newInstance());
                    } else {
                        if (TextUtils.isEmpty(editMoney.getText().toString())) {
                            ToastUtil.showShort("金额不能为空");
                        } else if (Integer.valueOf(editMoney.getText().toString()) < 1000) {
                            ToastUtil.showShort("金额不能少于1000");
                        } else {
                            deposit();
                        }
                    }
                }


                break;
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    /**
     * 我要出借
     */
    private void deposit() {
        mCustomPopupWindow = new CustomPopupWindow(getContext(), R.layout.deposit_item,
                DisPlayUtils.getWidthPx(), DisPlayUtils.getHeightPx(), new OnPopWinDisMisBack() {
            @Override
            public void onPopWindowDismiss() {
            }
        }) {
            @Override
            public void setData(View view) {
                ImageView back_img = view.findViewById(R.id.iv_back);
                back_img.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        dismissWindow();
                    }
                });
                Button btnOk = view.findViewById(R.id.btn_ok);
                btnOk.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        dismissWindow();
                        lend();
                    }
                });
                RelativeLayout rlPayWay = view.findViewById(R.id.rl_pay_way);
                final TextView PayWay = view.findViewById(R.id.tv_pay_way);
                final TextView amount = view.findViewById(R.id.tv_amount);
                amount.setText(editMoney.getText().toString() + "元");
                rlPayWay.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {

                    }
                });
            }
        };
        mCustomPopupWindow.showAsDownWindow(mLlBottom);
    }

    private void postGet(String pwd) {
        mItemsPresenter.chujie(new IViewRequest<String>() {
            @Override
            public void onFailMsg(String var) {
                mCustomPopupWindow.dismissWindow();
                ToastUtil.showShort(var);
            }

            @Override
            public void onCode(int code) {
                mCustomPopupWindow.dismissWindow();
                ToastUtil.showShort(code);
            }

            @Override
            public void onSuccess(Response<String> data) {
                ToastUtil.showShort("投资成功");
                EventBusActivityScope.getDefault(getActivity()).post(new EventBase("刷新界面"));
                mCustomPopupWindow.dismissWindow();
                _mActivity.onBackPressed();
            }

            @Override
            public void onFail(Response<String> error) {

            }
        }, mBundle.getString("proid"), editMoney.getText().toString(), pwd);
    }

    /**
     * 立即出借
     */
    private void lend() {
        mCustomPopupWindow = new CustomPopupWindow(getActivity().getWindow(), getContext(), R.layout.pay_money,
                DisPlayUtils.getWidthPx(), DisPlayUtils.getHeightPx(), new OnPopWinDisMisBack() {
            @Override
            public void onPopWindowDismiss() {

            }
        }) {
            @Override
            public void setData(View view) {
                ImageView back_img = view.findViewById(R.id.iv_back);
                back_img.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        dismissWindow();
                    }
                });
                final EditText editText = view.findViewById(R.id.password);
                Button button = view.findViewById(R.id.sure);
                button.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if (TextUtils.isEmpty(editText.getText().toString())) {
                            ToastUtil.showShort("请输入交易密码");
                        } else {
                            postGet(editText.getText().toString());
                        }

                    }
                });


            }
        };
        mCustomPopupWindow.showAsDownWindow(mLlBottom);
    }

    @Subscribe
    public void onTabSelectedEvent(EventBase event) {
        if (event.getName().equals("交易密码")) {
            getData(PreferenceManager.instance().getUseId());
        }
    }
}
